<template>
  <div v-if="editMarkDownVisible && access_token" style="height: 100%; overflow: hidden">
    <v-md-editor
      v-model="text"
      left-toolbar="undo redo clear | h bold italic strikethrough quote | ul ol table hr | image | save "
      :include-level="[1, 2, 3, 4, 5, 6]"
      :disabled-menus="[]"
      height="100%"
      @upload-image="handleUploadImage"
      @save="menuUpdateContent"
    />
  </div>
  <div v-else class="document_wrap" style="height: 100%; overflow-y: auto">
    <div class="documnet_menu">
      <div class="menu_top">
        <span v-if="access_token" style="cursor: pointer" @click="editMarkDownVisible = true">
          <i class="el-icon-notebook-2" />
        </span>
        <span>导读</span>
        <span>
          <i class="el-icon-search" />
        </span>
      </div>
      <div
        v-for="(anchor, index) in titles"
        :key="index"
        class="menu_item_wrap"
        :style="{ paddingLeft: `${anchor.indent * 14 + 16}px` }"
        @click="handleAnchorClick(anchor)"
      >
        <a style="cursor: pointer">{{ anchor.title }}</a>
      </div>
    </div>
    <div ref="document" class="preview_wrap">
      <v-md-preview ref="preview" class="preview_content" :text="text" />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { menuGetContent, menuUpdateContent, fileUpload } from '@/api/golangApi/menu'
// const text = localStorage.getItem('ticketsOperationDocument') || ''
// const text = `# 工单系统操作手册`

export default {
  name: 'Documnet',
  data() {
    return {
      text: '',
      editMarkDownVisible: false,
      titles: []
    }
  },
  computed: {
    ...mapGetters(['access_token'])
  },
  async mounted() {
    await this.menuGetContent()
    this.initMenu()
  },
  methods: {
    initMenu() {
      const anchors =
        this.$refs.preview.$el.querySelectorAll('h1,h2,h3,h4,h5,h6')
      const titles = Array.from(anchors).filter(
        (title) => !!title.innerText.trim()
      )
      if (!titles.length) {
        this.titles = []
        return
      }
      const hTags = Array.from(
        new Set(titles.map((title) => title.tagName))
      ).sort()
      this.titles = titles.map((el) => ({
        title: el.innerText,
        lineIndex: el.getAttribute('data-v-md-line'),
        indent: hTags.indexOf(el.tagName)
      }))
    },
    async menuGetContent() {
      try {
        const res = await menuGetContent({
          uuid: this.$route.name
        })
        if (res.code === 200) {
          this.text = res.data.content
        }
      } catch (error) {
        console.log(error)
      }
    },
    // md文档图片上传
    async handleUploadImage(event, insertImage, files) {
      // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
      const formData = new FormData()
      formData.append('file', files[0])
      const res = await fileUpload(formData)
      if (res.code === 200) {
        // 此处只做示例
        insertImage({
          url: res.data.url,
          desc: res.data.name
        // width: 'auto',
        // height: 'auto',
        })
      }
    },
    handleAnchorClick(anchor) {
      const { preview } = this.$refs
      const { lineIndex } = anchor
      const heading = preview.$el.querySelector(
        `[data-v-md-line="${lineIndex}"]`
      )
      if (heading) {
        // 注意：如果你使用的是编辑组件的预览模式,则这里的方法名改为 previewScrollToTarget
        preview.scrollToTarget({
          target: heading,
          scrollContainer: this.$refs.document,
          top: 60
        })
      }
    },
    async menuUpdateContent(text) {
      console.log(1231)
      this.text = text
      try {
        const res = await menuUpdateContent({
          uuid: this.$route.name,
          content: text
        })
        if (res.code === 200) {
          this.editMarkDownVisible = false
          this.$nextTick(() => {
            this.initMenu()
          })
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.document_wrap {
  display: flex;
  height: 100%;
  overflow-y: auto;
  .preview_wrap {
    background-color: #fff;
    flex: 1;
    height: 100%;
    overflow-y: auto;
    display: flex;
    justify-content: center;
    .preview_content {
      max-width: 1000px;
      transform: scale(0.8);
      transform-origin: top;
    }
  }
  .documnet_menu {
    background-color: #fafafa;
    border-right: 1px solid #eee;
    width: 260px;
    right: 10px;
    display: flex;
    flex-direction: column;
    .menu_top {
      padding: 16px;
      display: flex;
      justify-content: space-between;
    }
    .menu_item_wrap {
      padding: 4px 0;
      transition: all 0.3s ease;
      &:hover {
        background-color: #eeeeee;
        font-weight: 600;
      }
    }
  }
}
</style>
